package com.wdb.modules.xxlJob.jobHandler;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wdb.modules.xxlJob.domain.dto.HotSearchContentDTO;
import com.wdb.modules.xxlJob.domain.dto.HotSearchDTO;
import com.wdb.utils.PageResult;
import com.wdb.utils.PageUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.compress.utils.Lists;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * @author: wendaobai@qq.com
 * @date: 2024/9/12 星期四 16:41
 */
@Component
@Slf4j
public class DouyinHotSearchJob {

  // 抖音热搜爬虫
  public HotSearchDTO hotSearch(String paras) {
    log.info("hotSearch start---");
    try {
      OkHttpClient client = new OkHttpClient().newBuilder().build();
      Request request =
          new Request.Builder()
              .url("https://www.iesdouyin.com/web/api/v2/hotsearch/billboard/word/")
              .method("GET", null)
              .build();

      Response response = client.newCall(request).execute();
      JSONObject jsonObject = JSONObject.parseObject(response.body().string());
      // log.info("json--{}",jsonObject);
      JSONArray wordList = jsonObject.getJSONArray("word_list");
      HotSearchDTO hotSearchDTO = new HotSearchDTO();
      List<HotSearchContentDTO> hotSearchContentDTOS = Lists.newArrayList();
      for (int i = 0; i < wordList.size(); i++) {
        JSONObject obj =(JSONObject) wordList.get(i);
        HotSearchContentDTO hotSearchContentDTO = new HotSearchContentDTO();
        hotSearchContentDTO.setTitle(obj.getString("word"));
        hotSearchContentDTO.setHotValue(obj.getString("hot_value"));
        hotSearchContentDTO.setId(IdUtil.simpleUUID());
        hotSearchContentDTO.setUrl("https://www.douyin.com/search/" + hotSearchContentDTO.getTitle() + "?type=general");
        hotSearchContentDTOS.add(hotSearchContentDTO);
      }
      hotSearchDTO.setHotSearchContentDTOList(hotSearchContentDTOS);
      DateTime now = DateUtil.date(System.currentTimeMillis());
      hotSearchDTO.setUpdateTime(now);
      return  hotSearchDTO;
    } catch (IOException e) {
      log.info("hotSearch error---{}", e.getMessage());
      throw new RuntimeException(e);
    }

  }
}
